package cn.edu.bupt.blog.web.admin;

import cn.edu.bupt.blog.po.User;
import cn.edu.bupt.blog.service.UserService;
import cn.edu.bupt.blog.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {
    @Autowired
    private UserService userService;

    // 跳转到登录页
    @GetMapping
    public String loginPage() {
        return "admin/login";
    }

    // 登录
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password,
                        HttpSession session, RedirectAttributes attributes){
        // 根据用户名和密码查询用户
        User user = userService.checkUser(username, MD5Utils.code(password));
        if(user != null) {
            // 如果存在用户，为了密码安全，将用户的密码重置为空
            user.setPassword(null);
            session.setAttribute("user",user);
            // 跳转到首页
            return "admin/index";
        }else{
            // 不存在该用户
            attributes.addFlashAttribute("message","用户名或密码错误！");
            return "redirect:/admin";
        }
    }

    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.removeAttribute("user");
        return "redirect:/admin";
    }
}
